package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1.参数的校验
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //是否关注了
        Short operation = dto.getOperation();
        if (operation!=1&&operation!=0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"状态异常");
        }
        Integer userId = user.getId();
        Integer authorApUserId = dto.getAuthorApUserId();
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        // 关注
        if (operation==0){
            if (user.getId().equals(authorApUserId)){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自己不能关注自己的");
            }
            Double score = zSetOperations.score(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId));
            if (score!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已经关注了");
            }
            //2.关注作者， zadd follow ：登录人，作者  fans:作者 登录人
            zSetOperations.add(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId),System.currentTimeMillis());
            zSetOperations.add(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(userId),System.currentTimeMillis());
        }else {
            //3.取消关注, zrem
            zSetOperations.remove(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorApUserId));
            zSetOperations.remove(UserRelationConstants.FANS_LIST+authorApUserId,String.valueOf(userId));
        }
        return ResponseResult.okResult();
    }
}
